package com.carey.blog.jsonrpc.impl;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;

import com.carey.blog.framework.latke.action.ActionException;
import com.carey.blog.jsonrpc.AbstractGAEJSONRpcService;
import com.carey.blog.model.Statistic;
import com.carey.blog.repository.StatisticRepository;
import com.carey.blog.repository.impl.StatisticGAERepository;
import com.carey.blog.util.Users;

/**
 * Statistic service for JavaScript client.
 * 
 */
public final class StatisticService extends AbstractGAEJSONRpcService {

	/**
	 * Logger.
	 */
	private static final Logger LOGGER = Logger
			.getLogger(StatisticService.class.getName());
	/**
	 * Statistic repository.
	 */
	private StatisticRepository statisticRepository = StatisticGAERepository
			.getInstance();
	/**
	 * User utilities.
	 */
	private Users userUtils = Users.getInstance();

	/**
	 * Gets the blog statistic.
	 * 
	 * @param request
	 *            the specified http servlet request
	 * @param response
	 *            the specified http servlet response
	 * @return for example,
	 * 
	 *         <pre>
	 * {
	 *     "statisticBlogViewCount": int,
	 *     "statisticBlogCommentCount": int,
	 *     "statisticBlogArticleCount": int
	 * }
	 * </pre>
	 * 
	 *         , returns {@code null} if not found
	 * @throws ActionException
	 *             action exception
	 * @throws IOException
	 *             io exception
	 */
	public JSONObject getBlogStatistic(final HttpServletRequest request,
			final HttpServletResponse response) throws ActionException,
			IOException {
		if (!userUtils.isAdminLoggedIn()) {
			response.sendError(HttpServletResponse.SC_FORBIDDEN);
			return null;
		}

		JSONObject ret = new JSONObject();
		try {
			ret = statisticRepository.get(Statistic.STATISTIC);
		} catch (final Exception e) {
			LOGGER.log(Level.SEVERE, e.getMessage(), e);
		}

		return ret;
	}

	/**
	 * Gets the {@link StatisticService} singleton.
	 * 
	 * @return the singleton
	 */
	public static StatisticService getInstance() {
		return SingletonHolder.SINGLETON;
	}

	/**
	 * Private default constructor.
	 */
	private StatisticService() {
	}

	/**
	 * Singleton holder.
	 * 
	 */
	private static final class SingletonHolder {

		/**
		 * Singleton.
		 */
		private static final StatisticService SINGLETON = new StatisticService();

		/**
		 * Private default constructor.
		 */
		private SingletonHolder() {
		}
	}
}
